package kyssion.leetcode.num201_250;

import kyssion.leetcode.util.TreeNode;

public class code235_二叉搜索树的最近公共祖先 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (p.val > q.val) {
            return lowestCommonAncestor(root, q, p);
        }
        if (root == null) {
            return null;
        }
        if (p.val < root.val && q.val > root.val) {
            return root;
        } else if (q.val < root.val) {
            return lowestCommonAncestor(root.left, p, q);
        } else if (p.val > root.val) {
            return lowestCommonAncestor(root.right, p, q);
        } else if (root == p) {
            return p;
        } else if (root == q) {
            return q;
        } else {
            return null;
        }
    }
}
